package com.byit.controller;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.byit.async.AuthPushAsync;
import com.byit.builder.MapBuilder;
import com.byit.constant.DefaultValue;
import com.byit.domain.AppEnterpriseAuthentication;
import com.byit.domain.AppUser;
import com.byit.log.ChannelType;
import com.byit.log.Log;
import com.byit.log.OperatorType;
import com.byit.msg.MessageResult;
import com.byit.service.IAppEnterpriseAuthenticationService;
import com.byit.service.IAppUserService;
import com.byit.shrio.session.SessionHelper;
import com.byit.utils.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;


/**
 * APP企业认证管理
 *
 * @author tjm
 * @date 2019年1月9日
 */
@RestController
@RequestMapping("/api/sys/enterpriseAuth")
public class AppEnterpriseAuthenticationController {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private IAppEnterpriseAuthenticationService enterpriseAuthenticationService;
    @Autowired
    private IAppUserService appUserService;
    @Autowired
    private AuthPushAsync authPushAsync;


    /**
     * 查询详情
     */
    @Log(title = "企业认证", operate = OperatorType.DATA_SELECT, channel = ChannelType.WEB_INTER)
    @PostMapping("/details")
    public Object details(@RequestParam(name = "id") Long id) {
        Page<JSONObject> data = enterpriseAuthenticationService.selectPageData(new Page<>(1, 1), MapBuilder.newMap(1).setParam("id", id).ok());
        return MessageResult.success(data.getRecords().get(0));
    }

    /**
     * 查询列表
     */
    @Log(title = "企业认证", operate = OperatorType.DATA_SELECT, channel = ChannelType.WEB_INTER)
    @GetMapping("/list")
    public Object list(AppEnterpriseAuthentication authentication,
                       @RequestParam(value = "page", defaultValue = DefaultValue.PAGE_FIRST) int page,
                       @RequestParam(value = "limit", defaultValue = DefaultValue.PAGE_SIZE) int limit) {
        Page<AppEnterpriseAuthentication> pageInfo = new Page<>(page, limit);
        EntityWrapper<AppEnterpriseAuthentication> wrapper = new EntityWrapper<>();
        wrapper.setSqlSelect("id,status,phone,company_name as companyName,legal_name AS legalName,credit_no AS creditNo,id_card_no as idCardNo,create_time as createTime,update_time AS updateTime");
        wrapper.eq("is_del", 0);
        if (null != authentication.getStatus()) {
            wrapper.eq("status", authentication.getStatus());
        }
        if (null != authentication.getCreditNo()) {
            wrapper.like("credit_no", "%" + StringUtil.decodeSpecialCharsWhenLikeUseBackslash(authentication.getCreditNo()) + "%");
        }
        if (StringUtil.isNotEmpty(authentication.getLegalName())) {
            wrapper.like("legal_name", "%" + StringUtil.decodeSpecialCharsWhenLikeUseBackslash(authentication.getLegalName()) + "%");
        }
        if (StringUtil.isNotEmpty(authentication.getCompanyName())) {
            wrapper.like("company_name", authentication.getCompanyName());
        }
        if (StringUtil.isNotEmpty(authentication.getIdCardNo())) {
            wrapper.like("id_card_no", "%" + StringUtil.decodeSpecialCharsWhenLikeUseBackslash(authentication.getIdCardNo()) + "%");
        }
        if (StringUtil.isNotEmpty(authentication.getPhone())) {
            wrapper.like("phone", "%" + StringUtil.decodeSpecialCharsWhenLikeUseBackslash(authentication.getPhone()) + "%");
        }
        Page<AppEnterpriseAuthentication> appEnterpriseAuthenticationPage = enterpriseAuthenticationService.selectPage(pageInfo, wrapper);

        return MessageResult.success(appEnterpriseAuthenticationPage);
    }

    /**
     * 审核
     */
    @Log(title = "企业认证", operate = OperatorType.DATA_UPDATE, channel = ChannelType.WEB_INTER)
    @PostMapping("/audit")
    public Object audit(HttpSession session, @RequestParam("id") Long id,
                        @RequestParam("status") Integer status, String auditOpinion) {
        Long userId = SessionHelper.getUserId(session);
        //检查企业信用代码是否已被其他用户认证
        AppEnterpriseAuthentication selectById = enterpriseAuthenticationService.selectById(id);
        List<AppEnterpriseAuthentication> authenticationList = enterpriseAuthenticationService.selectByMap(MapBuilder.newMap(3).
                setParam("is_del", 0).setParam("credit_no", selectById.getCreditNo()).setParam("status", 2).ok());
        if (authenticationList.size() > 1) {
            return MessageResult.error("该企业信用代码已被其他用户认证");
        } else if (authenticationList.size() == 1) {
            if (!authenticationList.get(0).getUserId().equals(selectById.getUserId())) {
                return MessageResult.error("该企业信用代码已被其他用户认证");
            }
        }
        //检查公司名称是否已被其他用户认证
        List<AppEnterpriseAuthentication> companys = enterpriseAuthenticationService.selectByMap(MapBuilder.newMap(3).
                setParam("is_del", 0).setParam("company_name", selectById.getCompanyName()).setParam("status", 2).ok());
        if (companys.size() > 1) {
            return MessageResult.error("该公司名称已被其他用户认证");
        } else if (companys.size() == 1) {
            if (!companys.get(0).getUserId().equals(selectById.getUserId())) {
                return MessageResult.error("该公司名称代码已被其他用户认证");
            }
        }
        AppEnterpriseAuthentication authentication = new AppEnterpriseAuthentication();
        authentication.setUpdateTime(new Date());
        authentication.setOperationId(userId);
        authentication.setId(id);
        authentication.setStatus(status);
        if (StringUtil.isNotEmpty(auditOpinion)) {
            authentication.setAuditOpinion(auditOpinion);
        }
        if (enterpriseAuthenticationService.updateById(authentication)) {
            //认证成功修改app_user为企业用户
            //修改app_user表认证状态

            AppUser appUser = new AppUser();
            appUser.setId(selectById.getUserId());
            appUser.setType(1);
            appUser.setAuthState(status + 3);
            appUserService.updateById(appUser);
            //推送
            authPushAsync.sendMsg(selectById.getUserId(), status, 1);
            return MessageResult.success();
        }
        return MessageResult.error();
    }


}
